const express = require("express");

const jwt = require("jsonwebtoken");
// const cors = require("cors");


const bodyParser = require("body-parser");
const app = express();

const menuData = require("./data/menu");


// 解析JSON格式的请求体
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 中间件配置跨域
app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  next();
});

// 设置静态文件目录
app.use(express.static("public"));

app.get("/public/*", function (req, res) {
  res.sendFile(__dirname + "/" + req.url);
});

// 登录接口
// 密钥数据
const secretKey = "summer-love";
app.post("/login", (req, res) => {
  let { username, password } = req.body;
  if (username === "admin" && password === "12345") {
    // 生成Token
    const token = jwt.sign(req.body, secretKey, {
      expiresIn: "1h", // Token有效期为1小时
    });
    res.send({
      code: 200,
      token,
      id: "1001",
      user: username
    });
  } else {
    res.send({
      code: 201,
      message: '账号或密码错误'
    })
  }
});

// 获取路由接口
app.get("/routes", (req, res) => {
  if (req.query.id === "1000") {
    res.json({
      data: menuData.slice(0, 2),
    });
  } else if (req.query.id === "1001") {
    res.json({
      data: menuData,
    });
  }
});

const getFileInterface = require('./router/file')
getFileInterface(app)

const getHospitalInterface = require('./router/hospital')
getHospitalInterface(app)

const getProductApi = require('./router/product')
getProductApi(app)

app.listen(3000);
